package com.future.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.future.gateway.filter.constant.R;
import com.future.gateway.filter.constant.SecurityConstant;
import com.future.gateway.filter.constant.VerficationCode;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author Captain price
 * @version 1.0
 * @project future
 * @description 登录验证码校验
 * @date 2023/10/20 11:20:20
 */
@Slf4j
@Component
@AllArgsConstructor
public class CodeCheckFilter implements GlobalFilter, Ordered {
    @Resource
    RedisTemplate<String,String> redisTemplate;
    @Resource
    ObjectMapper objectMapper;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 判断是否登录请求
        if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(),
                SecurityConstant.OAUTH_TOKEN_URL, SecurityConstant.SMS_TOKEN_URL,
                SecurityConstant.SOCIAL_TOKEN_URL)) {
            log.info("当前请求为登录信息，不做处理");
            return chain.filter(exchange);
        }
        // 刷新token
        String grantType = request.getQueryParams().getFirst("grant_type");
        if (StrUtil.equals(SecurityConstant.REFRESH_TOKEN, grantType)) {
            log.info("当前请求为刷新token信息，不做处理");
            return chain.filter(exchange);
        }
        // 验证码校验
        try {
            String code = request.getQueryParams().getFirst("code");
            log.info("当前获取验证码为:{}", code);
            if (StrUtil.isBlank(code)) {
                throw new Exception("验证码不能为空");
            }
            String key = VerficationCode.CODE_PREFIX;
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
                throw new Exception("验证码输入错误");
            }
            Object codeObj = redisTemplate.opsForValue().get(key);
            if (codeObj == null) {
                throw new Exception("未获取到有效的验证码");
            }
            String saveCode = codeObj.toString();
            if (StrUtil.isBlank(saveCode)) {
                redisTemplate.delete(key);
                throw new Exception("未获取到有效的验证码");
            }
            if (!StrUtil.equals(saveCode, code)) {
                redisTemplate.delete(key);
                throw new Exception("验证码输入错误");
            }
            redisTemplate.delete(key);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
            try {
                return response.writeWith(Mono.just(response.bufferFactory()
                        .wrap(objectMapper.writeValueAsBytes(
                                R.failed(e.getMessage())))));

            } catch (Exception exception) {
                log.error("对象输出异常", exception);
            }
            return chain.filter(exchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
